package com.zxl.always.on.display.ui.widget.battery;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zxl.always.on.display.R;

/**
 * Created by Administrator on 2018/3/1.
 */

public class BatteryLayout extends RelativeLayout {

    private boolean mIsStartMonitor;

    private BatteryMeterView meterView;

    private TextView mBatteryCountView;

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            meterView.setBattery(intent);
            mBatteryCountView.setText((int) (meterView.getmBatteryLevel() * 100) + "%");
        }
    };

    public BatteryLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        meterView = findViewById(R.id.panel_battery_icon);
        mBatteryCountView = findViewById(R.id.panel_battery_count);

        if (isInEditMode()) {
            return;
        }
        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = getContext().registerReceiver(mIsStartMonitor ? mReceiver : null, ifilter);
        meterView.setBattery(batteryStatus);
        mBatteryCountView.setText((int) (meterView.getmBatteryLevel() * 100) + "%");
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mIsStartMonitor) {
            try {
                getContext().unregisterReceiver(mReceiver);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void setIsStartMonitor(boolean mIsStartMonitor) {
        try {
            this.mIsStartMonitor = mIsStartMonitor;
            if (mIsStartMonitor) {
                IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
                getContext().registerReceiver(mReceiver, ifilter);
            } else {
                getContext().unregisterReceiver(mReceiver);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
